package com.hj.security.engine;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ProgressDialog;
import android.util.Log;

public class DownloadTask {

	public static File getFile(String path, String filePath, ProgressDialog progressDialog) throws Exception{
		URL url = new URL(path);
		Log.i("url", url.toString());
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setReadTimeout(2000);
		connection.setRequestProperty("Accept-Charset", "iso-8859-1");
		connection.setRequestProperty("contentType", "iso-8859-1");
		connection.setRequestMethod("GET");
		Log.i("url", connection.getResponseCode()+"");
		if(connection.getResponseCode()==200){
			int total= connection.getContentLength();
			progressDialog.setMax(total);
			
			InputStream is = connection.getInputStream();
			File file = new File(filePath);
			OutputStream os = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int len;
			int process = 0;
			while((len=is.read(buffer))!=-1){
				os.write(buffer,0,len);
				process += len;
				progressDialog.setProgress(process);
			}
			os.flush();
			os.close();
			is.close();	
			return file;
		}
		return null;
	}
}
